//
//  NSString+DiskSize.m
//  框架
//
//  Created by mayanwei on 14-9-2.
//  Copyright (c) 2014年 mayanwei. All rights reserved.
//

#import "NSString+DiskSize.h"

@implementation NSString (DiskSize)

+ (NSString *)folderSizeAtPath:(NSString *)folderPath
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath])
        return @"0K";
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString *fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil)
    {
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [NSString fileSizeAtPath:fileAbsolutePath];
    }
    
    return [NSString transformedValue:folderSize / 1024];
}

+ (long long)fileSizeAtPath:(NSString *)filePath
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]) {
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

+ (NSString *)transformedValue:(long long)value
{
    double convertedValue = value;
    int multiplyFactor = 0;
    
    NSArray *tokens = [NSArray arrayWithObjects: @"K", @"M", @"G", @"T", nil];
    
    while (convertedValue > 1024)
    {
        convertedValue /= 1024;
        multiplyFactor++;
    }
    
    return [NSString stringWithFormat:@"%.1f%@",convertedValue, [tokens objectAtIndex:multiplyFactor]];
}

@end
